package com.biostime.qdingding.modules.sys.service;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.biostime.qdingding.common.service.CrudService;
import com.biostime.qdingding.common.utils.StringUtils;
import com.biostime.qdingding.modules.sys.dao.RoleDao;
import com.biostime.qdingding.modules.sys.entity.Menu;
import com.biostime.qdingding.modules.sys.entity.Role;
import com.biostime.qdingding.modules.sys.entity.RolePermissions;
import com.biostime.qdingding.modules.sys.entity.User;
import com.google.common.collect.Maps;

/**
 * 角色表Service
 * @author phil
 * @version 2015-11-06
 */
@Service
@Transactional(readOnly = true)
public class RoleService extends CrudService<RoleDao, Role> {

	@Autowired
	private RolePermissionsService rolePermissionsService;
	@Autowired
	private MenuService menuService;
	
	@Transactional
	public void save(Role role, HttpServletRequest request) {
		this.save(role);
		
		/**删掉所有权限**/
		RolePermissions exm = new RolePermissions();
		exm.setRoleId(StringUtils.toInteger(role.getId()));;
		rolePermissionsService.deleteAll(exm);
		
		/**获取所有的权限**/
		List<Menu> menuList = menuService.getAllMenu();
		
		for(Menu menu:menuList){
			String[] permissions = request.getParameterValues(String.format("cb_%s", menu.getId()));
			if(permissions!=null && permissions.length>0){
				for(String p : permissions){
					RolePermissions perm = new RolePermissions();
					perm.setPermissions(p);
					perm.setRoleId(StringUtils.toInteger(role.getId()));
					perm.setNavId(menu.getNavId());
					
					rolePermissionsService.save(perm);
				}
			}
		}
	}
	
	/**
	 * 获取用户允许授权的所有角色
	 * @param user 当前用户
	 * @return
	 */
	public List<Role> findListByUser(User user) {
		return this.findList(new Role());
	}

	public Map<String, String> findMapByUser(User user) {
		Map<String, String> map = Maps.newHashMap();
		List<Role> roles = dao.findListByUser(user);
		for(Role r : roles){
			if(!map.containsKey(r.getId())){
				map.put(r.getId(), "1");
			}
		}
		
		return map;
	}
}
